<?php

namespace app\servercertificate\service\certificate;
use app\manage\service\ApiBase;

/**
 * @author:      李颖
 * @DateTime:    2017-06-15 10:00:29
 * @Description: 证书
 */

class Certificate extends ApiBase
{
	
    protected $certificateLogic = 'app\servercertificate\logic\Certificate';
	protected $certificateV2Logic = 'app\servercertificate\logic\CertificateV2';
    protected $certificateValidate = 'app\servercertificate\validate\Certificate';
    protected $addFields = ['user_id'=>0,'goods_id'=>0,'goods_info'=>' ','order_info'=>'','product_code'=>' ','transfer_log'=>''];
    protected $searchFields = ['keywords'=>'','type'=>'','is_pick'=>'','is_transfer'=>'','cate_id'=>0,'price_start'=>0,'price_end'=>0,'symbol'=>'','search_fields'=>[],'status'=>'','uid'=>'','no_distribute_date'=>''];    

    /*获取简单的证书信息*/
    public function getSimpleCertiInfo(): array 
    {
        $data = $this->haveIssetReceiveData(['user_id'=>'', 'id'=>' ']);
        return $this->stepRun($data, 'getSimpleCertiInfo');
    }
    /*生成证书*/
    protected function _applyCertificate($data): array 
    {

        $checkData = $this->_checkAddCertificate($data);
        if($checkData['status'] != SUCCESS_STATUS){
            return $checkData;
        }

        return $this->logic($this->certificateLogic)->applyCertificate($data);
    }

    /*生成普通证书*/
    public function applyCommonCertificate(): array 
    {
        $data = $this->haveIssetReceiveData(['user_id'=>0,'goods_id'=>0,'goods_info'=>' ','product_code'=>' ']);
        $data['order_info'] = '';
        $data['transfer_log'] = '';
        $data['type'] = 'common';
        return $this->_applyCertificate($data);
    }

    /*艺货 - 根据订单信息 证书编码信息 生成高级证书*/
    public function applyAdvancedCertificate(): array 
    {
        $data = $this->haveIssetReceiveData(['user_id'=>0, 'order_info'=>[], 'product_code'=>[], 'pay_method'=>' ']);
        //检验数据的完整性
        $checkData = $this->_checkAdvancedCertificate($data);
        if($checkData['status'] != SUCCESS_STATUS){
            return $checkData;
        }
        return $this->logic($this->certificateLogic)->applyAdvancedCertificate($data);
    }

    /*检验高级证书数据*/
    protected function _checkAdvancedCertificate($data): array 
    {
        //检验订单里的信息
        if(!isset($data['order_info']['user_id'], $data['order_info']['goods_ids'], $data['order_info']['goods_infos'], $data['order_info']['order_code'], $data['order_info']['status'], $data['order_info']['exceptions_status'])){ return verify_err(null, '订单信息缺失'); }
        //检验订单里商品的信息
        foreach ($data['order_info']['goods_infos'] as $k => $v) {
            if(!isset($v['id'], $v['title'], $v['choose'], $v['profile_pic'], $v['product_code'], $v['app_id'], $v['other_app_read'], $v['is_public'])){ return verify_err(null, '订单中的商品信息缺失'); }
        }
        if($data['order_info']['user_id'] != $data['user_id']){ return verify_err(null, '该订单不属于您'); }
        if($data['order_info']['goods_numbers'] != count($data['product_code']))
        {
            return verify_err(null, '订单总商品个数与证书编码个数不对应'); 
        }
        return auto_success($data, '检验数据通过');
    }

    /*检验证书数据*/
    protected function _checkAddCertificate($data): array 
    {

        $validate = validate($this->certificateValidate);
  
        if( !$validate->check($data) ){ return verify_err(null, $validate->getError()); }
        if( !$validate->scene('checkGoodsInfo')->check($data['goods_info']) ){ return verify_err(null, $validate->getError()); }
        //规则不好写的在这里单独验证
        if(!isset($data['goods_info']['goods_attrs']['pattern']) || !isset($data['goods_info']['goods_attrs']['standard']) || !isset($data['goods_info']['orther_price'])){
            return verify_err(null, '商品信息中的断代/款识、规格信息、付款方式其中有一个为空');
        }
        if($data['type'] == 'advanced' && empty($data['order_info'])){
            return verify_err(null, '生成高级证书时，请传入订单信息');
        }

        $certificate = $this->logic($this->certificateLogic)->dbCertifiInfo($data);
        if($certificate){
            return verify_err(null, '该商品已拥有证书');
        }

        return auto_success($data, '传入数据无误');
    }

    /*管理员将证书作废*/
    public function invalid(): array 
    {
        $data = $this->receiveData(['id'=>0]);
        return $this->stepRun($data, 'invalid');
    }

    /*用户申请证书作废*/
    public function applyInvalid(): array 
    {
        $data = $this->receiveData(['id'=>0,'user_id'=>0]);
        return $this->stepRun($data, 'applyInvalid');
    }

    /*证书详情：['id'=>'eq','goods_id'=>'eq','user_id'=>'eq','status'=>'in'] $data['field'] */
    /*管理员获取某一证书详情*/
    public function certificateInfo(): array 
    {
        $data = $this->receiveData(['id'=>0]);
        return $this->stepRun($data, 'certificateInfo', 'certificateInfo');
    }

    /*未登录时查看某一证书详情 例如：不可查看订单信息与转让记录*/
    public function noLoginCertificateInfo(): array 
    {
        $data = $this->receiveData(['id'=>0]);
        /*$data['field'] = 'id,app_id,other_app_read,is_public,name,product_code,user_id,goods_id,goods_info,type,earnings,is_pick,is_recommend,apply_invalid,is_transfer,status,create_time,update_time,transfer_log,order_info';*/
        $data['status'] = ['1'];
        return $this->stepRun($data, 'certificateInfo', 'certificateInfo');
    }

    /*登录后的游客查看某一证书详情*/
    public function loginCertificateInfo(): array 
    {
        $data = $this->receiveData(['id'=>0]);
        $data['status'] = ['1'];
        return $this->stepRun($data, 'certificateInfo', 'certificateInfo');
    }

    /*登录后获取我的证书详情 获取我的证书详情 + 获取我已转让过的证书详情*/
    public function userCertificate(): array 
    {
        $data = $this->receiveData(['id'=>0, 'user_id'=>0]);
        return $this->stepRun($data, 'myCertificateInfo', 'certificateInfo');
    }

    /*修改证书的证书编号*/
    public function updateProductCode(): array 
    {
        $data = $this->receiveData(['id'=>0,'product_code'=>' ']);
        return $this->stepRun($data, 'updateProductCode');   
    }

    /*管理员审核某一证书*/
    public function auditOneCertificate(): array 
    {
        $data = $this->receiveData(['id'=>0,'status'=>' ']);
        return $this->stepRun($data, 'auditOneCertificate');
    }

    /*获取证书数量*/
    public function counts(): array 
    {
        $data = $this->receiveData(['type'=>'all']);
        return $this->stepRun($data, 'counts');
    }

    /*前台获取证书列表*/
    public function allCertiList(): array 
    {
        $issetData = $this->issetReceiveData($this->searchFields);
        $haveData = $this->receiveData(['page'=>1,'listRows'=>15]);
        $data = array_merge($issetData, $haveData);

        return $this->stepRun($data, 'allCertiList', 'searchFields');
    }

    /*获取某一用户的证书列表（由状态区分）*/
    public function userCertiList(): array 
    {
        $issetData = $this->haveIssetReceiveData(['keywords'=>'','type'=>'','is_pick'=>'','is_transfer'=>'', 'pick_up_code'=>''], []);
        $haveData = $this->haveIssetReceiveData(['user_id'=>0,'status'=>'','page'=>1,'listRows'=>15], []);
        $data = array_merge($issetData, $haveData);
        return $this->stepRun($data, 'getCertiList', 'userSearchFields');
    }

    /*后台获取不同状态下的证书列表*/
    public function adminAllCertiList(): array 
    {
        $issetData = $this->issetReceiveData($this->searchFields);
        $haveData = $this->receiveData(['status'=>' ','page'=>1,'listRows'=>15]);
        $data = array_merge($issetData, $haveData);

        return $this->stepRun($data, 'getCertiList', 'searchFields');
    }

    /*根据商品id数组获取该商品所对应的证书状态*/
    public function getStatusByGoodsId(): array 
    {
        $data = $this->haveIssetReceiveData(['goods_ids'=>[]]);
        return $this->stepRun($data, 'getStatusByGoodsId', 'getStatusByGoodsId');
    }

    /*我的证书 - 确认提货*/
    public function affirmPickUpGoods(): array 
    {
        $data = $this->haveIssetReceiveData(['user_id'=>0, 'id'=>0]);
        return $this->stepRun($data, 'affirmPickUpGoods');
    }

    /*获取别人转让给我的证书列表（我未处理）*/
    public function inHandCertificateList(): array 
    {
        $data = $this->haveIssetReceiveData(['user_id'=>0, 'page'=>1, 'listRows'=>15, 'type'=>' ']);
        return $this->stepRun($data, 'inHandCertificateList');
    }

    /*给多个证书进行积分派发操作*/
    public function integralDistribute(): array 
    {
        $data = $this->haveIssetReceiveData(['system_user_id'=>0,'system_user_name'=>'', 'yes_integral_distribute_info'=>[], 'no_integral_distribute_info'=>[], 'distribute_date'=>' ']);
        $integralDistributeInfo = array_merge($data['yes_integral_distribute_info'], $data['no_integral_distribute_info']);
        foreach ($integralDistributeInfo as $k => $v) {
            if(!isset($v['certificate_user_id'], $v['certificate_id'], $v['certificate_name'], $v['certificate_product_code'], $v['integral'], $v['remark'])){
                return verify_err(null, '积分派发信息错误');
            }
            if(!is_int($v['certificate_user_id']) || !is_int($v['certificate_id']) || !is_int($v['integral']) || $v['integral'] < 0){
                return verify_err(null, '积分派发信息错误');
            }
        }
        return $this->stepRun($data, 'integralDistribute');
    }

    /*后台根据证书ids获取证书列表信息（不分页）*/
    public function getCertiListByIds(): array 
    {
        $data = $this->haveIssetReceiveData(['certificate_ids'=>' ', 'type'=>'', 'is_pick'=>'', 'is_transfer'=>'', 'status'=>'']);
        return $this->stepRun($data, 'getCertiListByIds');
    }

    /*根据搜索条件获取派发记录列表（不分页）*/
    public function getCertificateDistributeList(): array 
    {
        $data = $this->haveIssetReceiveData(['certificate_ids'=>'', 'distribute_date'=>'']);
        if($data['certificate_ids'] == '' && $data['distribute_date'] == ''){
            return verify_err(null, '证书id和派发日期不能同时为空');
        }
        return $this->stepRun($data, 'getCertificateDistributeList');
    }

    /*根据搜索条件获取派发记录列表（分页）*/
    public function getDistributePageList(): array 
    {
        $data = $this->haveIssetReceiveData(['distribute_date'=>'', 'keywords'=>'', 'status'=>'','certificate_id'=>'', 'page'=>1, 'listRows'=>15], []);
        return $this->stepRun($data, 'getDistributePageList', 'getDistributePageList');
    }

    /*后台管理员获取需要派发积分的证书分页列表*/
    public function getNeedDistributeList(): array 
    {
        $data = $this->haveIssetReceiveData(['page'=>1, 'listRows'=>15, 'neq_distribute_time'=>'', 'cate_id'=>0, 'keywords'=>'']);
        return $this->stepRun($data, 'getNeedDistributeList');
    }
    //一周新增商品/总商品数量/在售商品数量
    public function certiIncreTendency(): array 
    {
        $data = $this->haveIssetReceiveData(['dbDateFormat'=>'%y-%m-%d', 'dateFormat'=>'y-m-d']);
        return $this->stepRun($data, 'certiIncreTendency');
    }
    /*--------------------------------------------------v2版本下的方法改动和新增--------------------------------------------*/
    // 获取出售中的证书列表
    // 每个商品获取最后一次交易的证书
    public function isSellCertificateList(): array 
    {
        $data = $this->haveIssetReceiveData(['user_name'=>'','user_id'=>'','page'=>1, 'listRows'=>15, 'keywords'=>'', 'cate_id'=>'', 'price_order'=>'desc']);
        return $this->stepRun($data, 'isSellCertificateList', '', $this->certificateValidate, $this->certificateV2Logic);
    }
    // 设置我的证书 出售中 出售价格 出售人群
    public function setMyCertificate(): array 
    {
        $data = $this->haveIssetReceiveData(['user_id'=>0, 'id'=>0, 'is_sell'=>'', 'sell_price'=>'', 'to_user_names'=>''], []);
        if($data['is_sell'] == '' && $data['sell_price'] == '' && $data['to_user_names'] == ''){
            return verify_err(null, '请至少设置一项');
        }
        if($data['is_sell'] == 1 && $data['sell_price'] == ''){
            return verify_err(null, '出售中的证书必须有价格');
        }
        return $this->stepRun($data, 'setMyCertificate', 'setMyCertificate', $this->certificateValidate, $this->certificateV2Logic);
    }
    // 获取某一商品下的所有在售证书
    public function getTypeCertificateList(): array 
    {
        $data = $this->haveIssetReceiveData(['page'=>1, 'listRows'=>15, 'goods_id'=>0, 'user_name'=>'', 'price_order'=>'desc']);
        return $this->stepRun($data, 'getTypeCertificateList', '', $this->certificateValidate, $this->certificateV2Logic);
    }
    // 对某一用户的证书进行还原设置
    public function restoreSettings(): array 
    {
        $data = $this->haveIssetReceiveData(['id'=>0]);
        return $this->stepRun($data, 'restoreSettings', '', $this->certificateValidate, $this->certificateV2Logic);
    }
    // 获取某个证书的价格走势图
    public function priceChart(): array 
    {
        $data = $this->haveIssetReceiveData(['certificate_id'=>0, 'unit'=>'5m', 'scope'=>'1w']);
        return $this->stepRun($data, 'priceChart', '', $this->certificateValidate, $this->certificateV2Logic);
    }
    // 获取只指给我的定向证书
    public function myDirectionalCerti(): array 
    {
        $data = $this->haveIssetReceiveData(['page'=>1,'listRows'=>15,'to_user_names'=>' ']);
        return $this->stepRun($data, 'myDirectionalCerti', '', $this->certificateValidate, $this->certificateV2Logic);
    }
    // 获取我的各种状态的高级证书  收益中、提货中、已提货、已出售、待接收   
    public function myAdvanceCertiByAction(): array 
    {
        $data = $this->haveIssetReceiveData(['user_id'=>0, 'user_name'=>'', 'action'=>' ', 'page'=>1, 'listRows'=>15]);
        if($data['action'] == 'is_receiving' && !$data['user_name']){
            return verify_err(null, '请传入用户账号');
        }
        return $this->stepRun($data, 'myAdvanceCertiByAction', '', $this->certificateValidate, $this->certificateV2Logic);
    }
    // 获取不同状态证书列表的价格筛选项
    public function getCertificateFilter(): array 
    {
        $data = $this->haveIssetReceiveData(['type'=>' ']);
        return $this->stepRun($data, 'getCertificateFilter', '', $this->certificateValidate, $this->certificateV2Logic);

    }
}






